﻿(function () {

    layui.use(["layer", "jquery", "table", "form", "tree"], function () {
        var layer = layui.layer;
        var $ = layui.jquery;
        var table = layui.table;
        var form = layui.form;
        var tree = layui.tree;

        $(document).ready(function () {
            $("#btnSearch").click(onBtnSearchClick);
            $("#btnViewStructure").click(onBtnViewStructureClick);

            table.render({
                elem: "#User",
                url: "/User/List",
                height: "full-69", // (10 + 38 + 10 + 10 + 1)
                page: false,
                method: "POST",
                where: getTableQueryParam(),
                even: true,
                parseData: function (res) {
                    //console.log(res);
                    return {
                        "code": res.Success == true ? 0 : -1,
                        "msg": res.Msg,
                        "count": res.Count,
                        "data": res.Data
                    };
                },
                cols: [[
                    { type: 'numbers', title: 'No.', width: 60, fixed: 'center' }
                    , { field: "Phone", width: 140, align: "center", title: "手机号码" }
                    , { field: "Name", width: 100, align: "center", title: "姓名" }
                    , { field: "InvitationCode", width: 100, align: "center", title: "邀请码" }
                    , { field: "ReferenceName", width: 100, align: "center", title: "推荐人" }
                    , { field: "ReferenceInvitationCode", width: 140, align: "center", title: "推荐人邀请码" }
                    , { field: "CreateTime", width: 200, align: "center", title: "创建时间" }
                    , { align: "center", title: "操作", toolbar: "#tableToolBar" }
                ]]
            });

            table.on("tool(user)", function (obj) {
                var layEvent = obj.event;

                if (layEvent == "tool-viewUserStructure") {
                    onViewUserStructureHandler(obj);
                }
                else if (layEvent == "tool-updateUser") {
                    onUpdateUserHandler(obj);
                }
                else if (layEvent == "tool-resetPwd") {
                    onResetPwdHandler(obj);
                }
            });
        });

        function getTableQueryParam() {
            return {
                Phone: $("#txtSearchPhone").val(),
                Name: $("#txtSearchName").val(),
                InvitationCode: $("#txtSearchInvitationCode").val(),
                Reference: $("#txtSearchReference").val(),
                ReferenceInvitationCode: $("#txtSearchReferenceInvitationCode").val()
            };
        }

        function onBtnSearchClick() {
            table.reloadData("User", {
                where: getTableQueryParam()
            });
        }

        function onBtnViewStructureClick() {
            var shopManagerUserId = $("#hdShopManagerUserId").val();
            showUserStructureDlg(shopManagerUserId);
        }

        function reloadTable() {
            $("#btnSearch").trigger("click");
        }

        function onViewUserStructureHandler(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;
            var userId = data.Id;
            showUserStructureDlg(userId);
        }

        function showUserStructureDlg(userId) {
            var _layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                area: ["350px", "80%"],
                offset: "10%",
                content: '<div Id="ViewUserStructureDlg2">' + $("#ViewUserStructureDlg").html() + '</div>'
            });

            var loadingIndex = layer.msg(addStyle("正在加载 ......"),
                { icon: 16, shade: 0.01, offset: ["25%"], time: false });
            $.ajax("/User/QueryUserStructure", {
                method: "POST",
                data: "UserId=" + userId,
                complete: function (jqXHR, textStatus) {
                    layer.close(loadingIndex);
                },
                success: function (data, textStatus, jqXHR) {
                    if (data.Success == true) {
                        handleData(data.Data);
                    } else {
                        layer.msg(addStyle("加载数据失败: " + data.Msg),
                            { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                        );
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.msg(addStyle("系统错误，请联系管理员！"),
                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                }
            });

            function handleData(data) {
                var treeData = Convert_2_TreeData(data, userId);
                var n = treeData.length;
                var dom = $("#ViewUserStructureDlg2 div").eq(0);
                tree.render({
                    elem: dom,
                    id: "Tree",
                    data: treeData
                });
            }
        }

        function Convert_2_TreeData(arr, rootUserId) {
            var arr2 = arr.filter(item => item["Id"] == rootUserId);
            if (arr2.length > 0) {
                var arr3 = [];
                arr.forEach((item, i) => {
                    var arr4 = arr.filter(item2 => item["InvitationCode"] == item2["ReferenceInvitationCode"]);
                    item["children"] = arr4;
                    arr3.push(item);
                });

                var root = arr2[0];
                var treeArr = [];
                var treeObj = Convert_2_TreeItemData(root);
                treeArr.push(treeObj);
                fun1(treeObj["obj"]["InvitationCode"], treeObj["children"]);
                return treeArr;
                function fun1(invitationCode, parent) {
                    var arr4 = arr3.filter(x => x["ReferenceInvitationCode"] == invitationCode);
                    if (arr4.length > 0) {
                        for (var i = 0; i < arr4.length; i++) {
                            var item2 = arr4[i];
                            var treeObj2 = Convert_2_TreeItemData(item2);
                            parent.push(treeObj2);
                            fun1(item2["InvitationCode"], treeObj2["children"]);
                        }
                    }
                }

                function Convert_2_TreeItemData(obj) {
                    return {
                        id: obj["Id"],
                        title: obj["Name"] + " - " + obj["Phone"],
                        obj: obj,
                        children: []
                    };
                }
            }
            return [];
        }

        function onUpdateUserHandler(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;
            var _userId = data.Id;

            var _layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                offset: "10%",
                content: '<div Id="UpdateUserInfoDlg2">' + $("#UpdateUserInfoDlg").html() + '</div>'
            });

            $("#UpdateUserInfoDlg2 input[name=txt-updateUserDlg-phone]").val(data["Phone"]);
            $("#UpdateUserInfoDlg2 input[name=txt-updateUserDlg-name]").val(data["Name"]);

            form.verify({
                name: [/[\u4e00-\u9fa5a-zA-Z0-9]{2,10}/, "姓名格式不正确！"]
            });

            form.on("submit(filter-updateUserDlg-ok)", function (data) {
                //console.log(data);

                layer.confirm("确定要修改数据吗？",
                    { icon: 3, title: "满堂创品", offset: "20%" },
                    function () {
                        var jsonData = {
                            UserId: _userId,
                            Phone: $("#UpdateUserInfoDlg2 input[name=txt-updateUserDlg-phone]").val(),
                            Name: $("#UpdateUserInfoDlg2 input[name=txt-updateUserDlg-name]").val()
                        };
                        //console.log(jsonData);

                        var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                            { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                        $.ajax("/User/UpdateUser", {
                            method: "POST",
                            data: jsonData,
                            complete: function (jqXHR, textStatus) {
                                layer.close(loadingIndex);
                            },
                            success: function (data, textStatus, jqXHR) {
                                if (data.Success == true) {
                                    layer.close(_layerId);
                                    layer.msg(addStyle("修改数据成功！"), {
                                        icon: 1, time: 1 * 1000, offset: ["25%"], end: function () {
                                            reloadTable();
                                        }
                                    });
                                } else {
                                    layer.msg(addStyle("修改数据失败: " + data.Msg),
                                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                                    );
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.msg(addStyle("系统错误，请联系管理员！"),
                                    { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                            }
                        });
                    }
                );

                return false;
            });
        }

        function onResetPwdHandler(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;
            var _userId = data.Id;

            var _layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                offset: "10%",
                content: '<div id="ResetPwdDlg2">' + $("#ResetPwdDlg").html() + '</div>'
            });

            $("#txt-resetPwdDlg-pwd").val("");
            $("#txt-resetPwdDlg-newPwd").val("");
            $("#txt-resetPwdDlg-newPwd2").val("");

            form.verify({
                pwd: [/\w{6,20}/, "密码格式不正确！"],
                pwd2: function (value, elem) {
                    if ($("#txt-resetPwdDlg-newPwd").val() != $("#txt-resetPwdDlg-newPwd2").val()) {
                        return "两次新密码输入不一致！"
                    }
                    return;
                }
            });

            form.on("submit(filter-resetPwdDlg-ok)", function (data) {
                //console.log(data);

                layer.confirm("确定要重设密码吗？",
                    { icon: 3, title: "满堂创品", offset: "20%" },
                    function () {
                        var jsonData = {
                            Pwd: hex_md5($("#txt-resetPwdDlg-pwd").val()).toUpperCase(),
                            NewPwd: hex_md5($("#txt-resetPwdDlg-newPwd").val()).toUpperCase(),
                            UserId: _userId
                        };
                        //console.log(jsonData);

                        var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                            { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                        $.ajax("/User/ResetPwd", {
                            method: "POST",
                            data: jsonData,
                            complete: function (jqXHR, textStatus) {
                                layer.close(loadingIndex);
                            },
                            success: function (data, textStatus, jqXHR) {
                                if (data.Success == true) {
                                    layer.close(_layerId);
                                    layer.msg(addStyle("重设密码成功！"), {
                                        icon: 1, time: 1 * 1000, offset: ["25%"], end: function () {
                                            reloadTable();
                                        }
                                    });
                                } else {
                                    layer.msg(addStyle("重设密码失败: " + data.Msg),
                                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                                    );
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.msg(addStyle("系统错误，请联系管理员！"),
                                    { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                            }
                        });
                    }
                );

                return false;
            });
        }

        function addStyle(str) {
            return '<span style="font-size: 16px;">' + str + '</span>';
        }
    });

})();